<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 https://www.meoyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 喵云科技 【https://www.meoyun.com】
// +----------------------------------------------------------------------

namespace app\api\controller;

use app\model\MessageModel;
use app\model\UsersModel;

class Message extends BaseApi
{
    protected ?string $dataModel = MessageModel::class;
    protected array $allowSearch = ['type', 'status', 'sender_id', 'receiver_id'];

    /**
     * 获取消息列表
     *
     * @return mixed
     */
    public function getMessageList()
    {
        try {
            // 获取当前用户ID
            $userId = $this->getUserId(true);
            
            // 获取参数
            $type = input('type', 0);
            $limit = input('limit', 20);
            
            // 参数验证
            if (!in_array($type, [0, 1, 2, 3, 4, 5, 6])) {
                return $this->fail('消息类型参数无效');
            }
            
            if ($limit > 50) {
                $limit = 50; // 限制每页最大数量
            }
            
            // 构建查询条件
            $query = MessageModel::where('to_uid', $userId);
            
            // 根据类型筛选
            switch ($type) {
                case 1: // 点赞和收藏
                    $query->whereIn('type', [MessageModel::TYPE_LIKE, MessageModel::TYPE_COLLECT]);
                    break;
                case 2: // 关注
                    $query->where('type', MessageModel::TYPE_FOLLOW);
                    break;
                case 3: // 评论
                    $query->where('type', MessageModel::TYPE_COMMENT);
                    break;
                case 4: // 系统通知
                    $query->where('type', MessageModel::TYPE_SYSTEM);
                    break;
                case 5: // 公告
                    $query->where('type', MessageModel::TYPE_ANNOUNCEMENT);
                    break;
                case 0: // 全部
                default:
                    // 不添加类型筛选
                    break;
            }
            
            // 执行查询
            $list = $query->with(['fromUser', 'post'])
                ->orderBy('created_at', 'desc')
                ->paginate($limit);
            
            return $this->dataByPage($list);
            
        } catch (\Exception $e) {
            return $this->fail('获取消息列表失败');
        }
    }
    
    /**
     * 标记消息为已读
     *
     * @return mixed
     */
    public function markAsRead()
    {
        try {
            // 获取当前用户ID
            $userId = $this->getUserId(true);

            // 获取参数
            $messageId = input('message_id');
            $type = input('type');
            
            // 参数验证
            if ($messageId) {

                $message = MessageModel::where('id', $messageId)
                    ->where('to_uid', $userId)
                    ->first();
                    
                if (!$message) {
                    return $this->fail('消息不存在');
                }
                
                $result = $message->markAsRead();
                
            } else if ($type !== null) {
                // 批量标记某类型消息为已读
                if (!in_array($type, [1, 2, 3, 4, 5, 6])) {
                    return $this->fail('消息类型参数无效');
                }
                
                $query = MessageModel::where('to_uid', $userId)
                    ->where('status', MessageModel::STATUS_UNREAD);
                
                // 根据类型筛选
                switch ($type) {
                    case 1:
                        $query->whereIn('type', [MessageModel::TYPE_LIKE, MessageModel::TYPE_COLLECT]);
                        break;
                    case 2:
                        $query->where('type', MessageModel::TYPE_FOLLOW);
                        break;
                    case 3:
                        $query->where('type', MessageModel::TYPE_COMMENT);
                        break;
                    case 4:
                        $query->where('type', MessageModel::TYPE_SYSTEM);
                        break;
                    case 5:
                        $query->where('type', MessageModel::TYPE_ANNOUNCEMENT);
                        break;
                }
                
                $result = $query->update(['status' => MessageModel::STATUS_READ]);
                
            } else {
                return $this->fail('请提供消息ID或消息类型');
            }
            
            if ($result) {
                return $this->success('标记成功');
            } else {
                return $this->fail('标记失败');
            }
            
        } catch (\Exception $e) {
            return $this->fail('操作失败，请稍后重试');
        }
    }
    
    /**
     * 获取消息统计信息
     *
     * @return mixed
     */
    public function getMessageStats()
    {
        try {
            // 获取当前用户ID
            $userId = $this->getUserId(true);
            
            // 基础查询条件
            $baseWhere = [
                'to_uid' => $userId,
                'status' => MessageModel::STATUS_UNREAD
            ];
            
            // 统计各类型未读消息数量
            $likeCollectCount = MessageModel::where($baseWhere)
                ->whereIn('type', [MessageModel::TYPE_LIKE, MessageModel::TYPE_COLLECT])
                ->count();
                
            $followCount = MessageModel::where($baseWhere)
                ->where('type', MessageModel::TYPE_FOLLOW)
                ->count();
                
            $commentCount = MessageModel::where($baseWhere)
                ->where('type', MessageModel::TYPE_COMMENT)
                ->count();
                
            $systemCount = MessageModel::where($baseWhere)
                ->where('type', MessageModel::TYPE_SYSTEM)
                ->count();
                
            $announcementCount = MessageModel::where($baseWhere)
                ->where('type', MessageModel::TYPE_ANNOUNCEMENT)
                ->count();
                
            // 总未读数量
            $totalCount = MessageModel::where($baseWhere)->count();
            
            // 获取最新公告消息
            $latestAnnouncements = MessageModel::where('to_uid', $userId)
                ->where('type', MessageModel::TYPE_ANNOUNCEMENT)
                ->with(['fromUser:id,nickname,avatar'])
                ->orderBy('created_at', 'desc')
                ->limit(5)
                ->get();
            
            $data = [
                'like_collect_count' => $likeCollectCount,
                'follow_count' => $followCount,
                'comment_count' => $commentCount,
                'system_count' => $systemCount,
                'announcement_count' => $announcementCount,
                'total_count' => $totalCount,
                'latest_announcements' => $latestAnnouncements
            ];
            
            return $this->success($data);
            
        } catch (\Exception $e) {
            return $this->fail('获取消息统计失败',2004);
        }
    }
    
    /**
     * 获取系统通知对话列表
     *
     * @return mixed
     */
    public function getSystemNotificationList()
    {
        try {
            // 获取当前用户ID
            $userId = $this->getUserId(true);
            
            // 获取参数
            $fromUserId = input('from_user_id');
            $limit = input('limit', 20);
            
            // 参数验证
            if (!$fromUserId || !is_numeric($fromUserId) || $fromUserId <= 0) {
                return $this->fail('发送者用户ID无效');
            }
            
            if ($limit > 50) {
                $limit = 50;
            }
            
            // 获取双向系统通知消息
            $messages = MessageModel::where('type', MessageModel::TYPE_SYSTEM)
                ->where(function($query) use ($userId, $fromUserId) {
                    $query->where(function($q) use ($userId, $fromUserId) {
                        $q->where('from_uid', $fromUserId)->where('to_uid', $userId);
                    })->orWhere(function($q) use ($userId, $fromUserId) {
                        $q->where('from_uid', $userId)->where('to_uid', $fromUserId);
                    });
                })
                ->with(['fromUser:id,nickname,avatar', 'toUser:id,nickname,avatar'])
                ->orderBy('created_at', 'asc')
                ->limit($limit)
                ->get();
            
            return $this->success($messages);
            
        } catch (\Exception $e) {
            return $this->fail('获取系统通知列表失败');
        }
    }
    
    /**
     * 删除消息
     *
     * @return mixed
     */
    public function deleteMessage()
    {
        try {
            // 获取当前用户ID
            $userId = $this->getUserId(true);
            
            // 获取参数
            $messageId = input('message_id');
            
            // 参数验证
            if (!$messageId || !is_numeric($messageId) || $messageId <= 0) {
                return $this->fail('消息ID无效');
            }
            
            // 查找消息
            $message = MessageModel::where('id', $messageId)
                ->where('to_uid', $userId)
                ->first();
                
            if (!$message) {
                return $this->fail('消息不存在');
            }
            
            // 软删除消息
            $result = $message->softDelete();
            
            if ($result) {
                return $this->success('删除成功');
            } else {
                return $this->fail('删除失败');
            }
            
        } catch (\Exception $e) {
            return $this->fail('删除失败，请稍后重试');
        }
    }
    
    /**
     * 获取消息详情
     *
     * @return mixed
     */
    public function getMessageDetail()
    {
        try {
            // 获取当前用户ID
            $userId = $this->getUserId(true);
            
            // 获取参数
            $messageId = input('message_id');
            
            // 参数验证
            if (!$messageId || !is_numeric($messageId) || $messageId <= 0) {
                return $this->fail('消息ID无效');
            }
            
            // 查找消息
            $message = MessageModel::where('id', $messageId)
                ->where('to_uid', $userId)
                ->where('status', '!=', MessageModel::STATUS_DELETED)
                ->with([
                    'fromUser:id,nickname,avatar',
                    'post:id,title,content',
                    'comment:id,content'
                ])
                ->first();
                
            if (!$message) {
                return $this->fail('消息不存在');
            }
            
            // 如果消息未读，标记为已读
            if ($message->status == MessageModel::STATUS_UNREAD) {
                $message->markAsRead();
            }
            
            return $this->success('获取成功', $message);
            
        } catch (\Exception $e) {
            return $this->fail('获取消息详情失败');
        }
    }
}